<template>
	<view class="ticket-order-page">
		<view :class="['jq_tics', list.length <= 1 ? 'jq_tics_noAfter' : 'jq_tics']">
			<view class="tit">
				<text>景区门票</text>
				<view class="tit_rt" @click="link(`/page_my/ticket/list?type=jq`)">
					<text class="more">查看全部</text>
					<image class="close" :src="`${img_baseUrl}/statics/std/static/arr_go.png`" mode=""></image>
				</view>
			</view>
			<view class="ticket-list" v-if="list && list.length">
				<view class="ticket-item" v-for="(item, index) in list" :key="item.orderId">
					<view class="ticket-title">
						<view class="title">
							<image :src="img_baseUrl + item.commonPic"></image>
							<text>{{ item.commonName }}</text>
						</view>
						<view :class="['status', `status_${item.orderStatus}`]">
							{{ item.orderStatus | orderStatusFilter }}
						</view>
					</view>
					<view class="ticket-cards" @click.stop="link(index == 1 ? `/page_my/ticket/list?type=jq` : `/page_my/ticket/detail?id=${item.orderId}&type=jq`)">
						<view class="ticket-card" v-for="it in item.detailPageVoList || []" :key="it.orderDetailsId">
							<view class="top">
								<view class="ticket-name">{{`${it.ticketName}`}}</view>
								<view class="ticket-price">¥{{ it.ticketMoney.toFixed(2) }}</view>
							</view>
							<view class="bottom">
								<view class="ticket-validity">{{it.ticketUsetimeStart}}<text class="tcan">至</text>{{it.ticketUsetimeEnd}}<text class="tcan">可用</text></view>
								<view class="tnum">{{it.ticketCount}}张</view>
							</view>
						</view>
					</view>
          <view class="pay">
          	<text>{{item.orderStatus == 1 ? '应付金额' : '实付金额'}}</text>
          	<text :class="[`status_${item.orderStatus}`]">¥{{ (item.orderTotalPrice / 100).toFixed(2) }}</text>
          </view>
					<view class="btns">
						<block v-if="item.orderStatus == 1">
							<view class="btn outline" @click.stop="cancelOrder(item.orderId, 'jq')">取消订单</view>
							<view class="btn primary" @click.stop="link(`/page_my/ticket/detail?id=${item.orderId}&type=jq`)">
								去支付
							</view>
						</block>
						<block v-if="item.orderStatus == 2">
							<view class="btn outline icon-service" @click.stop="callNiMa(item.phone)">
								联系客服
							</view>
						</block>
						<block v-if="item.orderStatus == 3">
							<view class="btn outline" @click.stop="delOrder(item.orderId, 'jq')">删除订单</view>
						</block>
					</view>
				</view>
			</view>
			<view class="noData" v-if="list && list.length === 0">
				<image :src="`${img_baseUrl}/statics/std/static/noData.png`"></image>
				<text>暂无数据</text>
			</view>
		</view>
		<view :class="['act_tics', list1.length > 1 ? 'act_tics' : 'act_tics_noAfter']">
			<view class="tit">
				<text>活动门票</text>
				<view class="tit_rt" @click="link(`/page_my/ticket/list?type=act`)">
					<text class="more">查看全部</text>
					<image class="close" :src="`${img_baseUrl}/statics/std/static/go.png`" mode=""
						></image>
				</view>
			</view>
			<view class="ticket-list" v-if="list1 && list1.length">
				<view class="ticket-item" v-for="(item, index) in list1" :key="item.orderId">
					<view class="ticket-title">
						<view class="title">
							<image :src="img_baseUrl + item.commonPic"></image>
							<text>{{ item.commonName }}</text>
						</view>
						<view :class="['status', `status_${item.orderStatus}`]">
							{{ item.orderStatus | orderStatusFilter }}
						</view>
					</view>
					<view class="ticket-cards" @click.stop="link(index == 1 ? `/page_my/ticket/list?type=jq` : `/page_my/ticket/detail?id=${item.orderId}&type=jq`)">
						<view class="ticket-card" v-for="it in item.detailPageVoList || []" :key="it.orderDetailsId">
							<view class="top">
								<view class="ticket-name">{{`${it.ticketName}`}}</view>
								<view class="ticket-price">¥{{ it.ticketMoney.toFixed(2) }}</view>
							</view>
							<view class="bottom">
								<view class="ticket-validity">{{it.ticketUsetimeStart}}<text class="tcan">至</text>{{it.ticketUsetimeEnd}}<text class="tcan">可用</text></view>
								<view class="tnum">{{it.ticketCount}}张</view>
							</view>
						</view>
					</view>
					<view class="pay">
						<text>{{item.orderStatus == 1 ? '应付金额' : '实付金额'}}</text>
						<text :class="[`status_${item.orderStatus}`]">¥{{ (item.orderTotalPrice / 100).toFixed(2) }}</text>
					</view>
					<view class="btns">
						<block v-if="item.orderStatus == 1">
							<view class="btn outline" @click.stop="cancelOrder(item.orderId, 'act')">取消订单</view>
							<view class="btn primary" @click.stop="link(`/page_my/ticket/detail?id=${item.orderId}&type=act`)">
								去支付
							</view>
						</block>
						<block v-if="item.orderStatus == 2">
							<view class="btn outline icon-service" @click.stop="callNiMa(item.phone)">
								联系客服
							</view>
						</block>
						<block v-if="item.orderStatus == 3">
							<view class="btn outline" @click.stop="delOrder(item.orderId, 'act')">删除订单</view>
						</block>
					</view>
				</view>
			</view>
			<view class="noData" v-if="list1 && list1.length === 0">
				<image :src="`${img_baseUrl}/statics/std/static/noData.png`"></image>
				<text>暂无数据</text>
			</view>
		</view>

	</view>
</template>

<script>
	import vTabs from "@/components/tabs.vue";
	import dayjs from "dayjs";
	import {
		requestGet
	} from "@/utils/request";
	import {
		ticketOrderStatus
	} from "@/utils/constant";

	export default {
		components: {
			vTabs
		},
		data() {
			return {
				img_baseUrl: process.env.VUE_APP_BASEURL_IMG_API,
				tabs: [{
						label: "",
						text: "全部",
					},
					{
						label: 1,
						text: "待支付",
					},
					{
						label: 2,
						text: "已支付",
					},
					{
						label: 4,
						text: "已核销",
					},
				],
				list: [],
				current: 1,
				activeTab: "",
				total: 0,
				loadAll: false, // 已加载全部
				keyId: 0,
				newGet: null,
				total1: 0,
				list1: []
			};
		},
		filters: {
			orderStatusFilter: function(value) {
				return ticketOrderStatus[value] || "null";
			},
		},
		onShow() {
			this._getList();
			this._getList1();
		},
		methods: {
			goMore(type) {
				
			},
			_getList() {
				let _this = this
				_this.nowGet = uni.request({
					url: process.env.VUE_APP_BASEURL_API +
						"/order/scenicTicketBusinessOrder/listApplectScenicTicketOrder",
					data: {
						orderStatus: _this.activeTab,
						pageNum: _this.current,
						orderType: 1,
						pageSize: 10,
					},
					header: {
						"content-type": "application/json;charset=UTF-8",
						Authorization: "Bearer " + uni.getStorageSync("X-Token"),
					},
					method: "GET",
					dataType: "json",
					success: (res) => {
						if (res.data.code === 200) {
							_this.total = res.data.total;
							res.data.rows.forEach((item) => {
								item.detailPageVoList = item.detailPageVoList.map((v) => Object.assign(
									v, {
										ticketUsetimeStart: dayjs(v.ticketUsetimeStart).format(
											'MM-DD HH:mm'),
										ticketUsetimeEnd: dayjs(v.ticketUsetimeEnd).format(
											'MM-DD HH:mm')
									}));
								item.commonName = item.detailPageVoList[0]?.commonName;
								item.commonPic = item.detailPageVoList[0]?.goodPic;
							});
							if (res.data.total > 1) {
								_this.list = res.data.rows.splice(0, 2)
							} else {
								_this.list = res.data.rows
							}
							// _this.list = _this.current === 1 ? res.data.rows : _this.list.concat(res.data
							// 	.rows);
							_this.keyId++;
						} else if (res.data.code === 401) {
							_this.status401();
						} else {
							_this.list = [];
						}
						uni.hideLoading();
					},
					fail: () => {
						_this.list = [];
						uni.hideLoading();
					}
				});
			},
			_getList1() {
				let _this = this
				_this.nowGet = uni.request({
					url: process.env.VUE_APP_BASEURL_API +
						"/order/activityTicketBusinessOrder/listApplectActivityTicketOrder",
					data: {
						orderStatus: _this.activeTab,
						pageNum: _this.current,
						orderType: 1,
						pageSize: 10,
					},
					header: {
						"content-type": "application/json;charset=UTF-8",
						Authorization: "Bearer " + uni.getStorageSync("X-Token"),
					},
					method: "GET",
					dataType: "json",
					success: (res) => {
						if (res.data.code === 200) {
							_this.total1 = res.data.total;
							res.data.rows.forEach((item) => {
								item.detailPageVoList = item.detailPageVoList.map((v) => Object.assign(
									v, {
										ticketUsetimeStart: dayjs(v.ticketUsetimeStart).format(
											'MM-DD HH:mm'),
										ticketUsetimeEnd: dayjs(v.ticketUsetimeEnd).format(
											'MM-DD HH:mm')
									}));
								item.commonName = item.detailPageVoList[0]?.commonName;
								item.commonPic = item.detailPageVoList[0]?.goodPic;
							});
							if (res.data.total > 1) {
								_this.list1 = res.data.rows.splice(0, 2)
							} else {
								_this.list1 = res.data.rows
							}
							// _this.list1 = _this.current === 1 ? res.data.rows : _this.list.concat(res.data
							// 	.rows);
							_this.keyId++;
						} else if (res.data.code === 401) {
							_this.status401();
						} else {
							_this.list1 = [];
						}
						uni.hideLoading();
					},
					fail: () => {
						_this.list1 = [];
						uni.hideLoading();
					}
				});
			},
			status401() {
				uni.showModal({
					title: "提示",
					content: "登录状态已过期，请重新登录",
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							uni.removeStorageSync("X-Token");
							uni.removeStorageSync("X-UserInfo");
							uni.navigateTo({
								url: "/pages/login/index",
							});
						} else if (res.cancel) {
							console.log("用户点击取消");
							uni.removeStorageSync("X-Token");
							uni.removeStorageSync("X-UserInfo");
						}
					},
				});
			},
			changeType(e) {
				this.list = []
				this.total = 0
				this.keyId = 0
				if (this.newGet) {
					this.nowGet.abort()
					this.newGet = null
				}
				this.activeTab = e.type;
				this.current = 1;
				uni.showLoading({
					title: "加载中",
				});
				this._getList();
			},
			link(url) {
				uni.navigateTo({
					url,
				});
			},
			// 取消订单
			cancelOrder(id, type) {
				const _this = this;
				uni.showModal({
					title: "提示",
					content: "确定要取消该订单吗？",
					success: function(res) {
						if (res.confirm) {
							let api;
							if (type == 'jq') {
								api = `/order/scenicTicketBusinessOrder/cancleOrder/${id}`
							} else if (type == 'act') {
								api = `/order/activityTicketBusinessOrder/cancleOrder/${id}`
							}
							requestGet(api).then((res) => {
								if (res.code === 200) {
									uni.showToast({
										title: "已取消",
										icon: "none"
									});
									if (type == 'jq') {
										_this._getList();
									} else if (type == 'act') {
										_this._getList1();
									}
								}
							});
						} else if (res.cancel) {
							console.log("用户点击取消");
						}
					},
				});
			},
			//     删除订单
			delOrder(id, type) {
				const _this = this;
				uni.showModal({
					title: "提示",
					content: "确定要删除该订单吗？",
					success: function(res) {
						if (res.confirm) {
							let api;
							if (type == 'jq') {
								api = `/order/scenicTicketBusinessOrder/deleteOrder/${id}`
							} else if (type == 'act') {
								api = `/order/activityTicketBusinessOrder/deleteOrder/${id}`
							}
							requestGet(api).then((res) => {
								if (res.code === 200) {
									uni.showToast({
										title: "已删除",
										icon: "none"
									});
									_this.current = 1;
									if (type == 'jq') {
										_this._getList();
									} else if (type == 'act') {
										_this._getList1();
									}
								}
							});
						} else if (res.cancel) {
							console.log("用户点击取消");
						}
					},
				});
			},
			// 支付前获取订单详细
			getPayOrderInfo: function(orderId) {
				if (this.isSubmitting) return;
				this.isSubmitting = true;
				requestGet(`/order/order/payOrder/${orderId}`).then((res) => {
					if (res.code === 200) {
						//调用微信官方支付接口弹出付款界面,输入密码扣款
						wx.requestPayment({
							provider: "wxpay",
							timeStamp: String(Date.now()),
							nonceStr: "A1B2C3D4E5",
							package: "prepay_id=wx20180101abcdefg",
							signType: "MD5",
							paySign: "",
							success: function(res) {
								console.log("success:" + JSON.stringify(res));
								uni.navigateTo({
									url: `/page_index/ticket/result?state=1&id=${orderId}`,
								});
							},
							fail: function(err) {
								console.log("fail:" + JSON.stringify(err));
								uni.navigateTo({
									url: `/page_index/ticket/result?state=0&id=${orderId}`,
								});
							},
						});
						this.isSubmitting = false;
					}
				});
			},
			// 拨打电话
			callNiMa(phone) {
				if (!phone) {
					uni.showToast({
						title: "暂无联系电话",
						icon: "none",
					});
					return;
				}
				uni.makePhoneCall({
					phoneNumber: phone,
				});
			},
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {
			if (this.list?.length < this.total) {
				this.current = this.current + 1;
				this._getList();
			} else {
				this.loadAll = true;
			}
		},
		async onPullDownRefresh() {
			console.log("refresh");
			this.current = 1;
			await this._getList();
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 400);
		},
	};
</script>

<style lang="scss">
	.act_tics_noAfter {
		background: #F0EDDD;
		border-radius: 24rpx;
		display: flex;
		flex-direction: column;
		min-height: 598rpx;
		max-height: 824rpx;
		position: relative;
		overflow: hidden;
		&::after {
			content: none;
			width: 0;
			height: 0;
		}
	}
	.act_tics {
		background: #F3EFE6;
		border-radius: 24rpx;
		display: flex;
		flex-direction: column;
		min-height: 598rpx;
		max-height: 824rpx;
		position: relative;
		overflow: hidden;
		
		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			width: 100%;
			height: 96rpx;
			z-index: 2;
			background: linear-gradient(180deg, rgba(243,239,230,0) 0%, #F3EFE6 75%, #F3EFE6 100%);
		}
	}
	.jq_tics_noAfter {
		background: #DCE5F0;
		border-radius: 24rpx;
		display: flex;
		flex-direction: column;
		min-height: 598rpx;
		max-height: 824rpx;
		position: relative;
		margin-bottom: 24rpx;
		overflow: hidden;
		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			width: 0;
			height: 0;
			z-index: 0;
			background: transparent;
		}
	}
	.jq_tics {
		background: #E0EDE5;
		border-radius: 24rpx;
		display: flex;
		flex-direction: column;
		min-height: 598rpx;
		max-height: 824rpx;
		position: relative;
		margin-bottom: 24rpx;
		overflow: hidden;

		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			width: 100%;
			height: 96rpx;
			z-index: 2;
			background: linear-gradient(180deg, rgba(220, 229, 240, 0) 0%, #DCE5F0 75%, #DCE5F0 100%);
		}
	}
	
	.tit {
		width: 100%;
		box-sizing: border-box;
		padding: 24rpx 32rpx 0 32rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	
		text {
			height: 48rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: rgba(0, 0, 0, 0.9);
			line-height: 48rpx;
		}
	
		image {
			width: 32rpx;
			height: 32rpx;
			display: flex;
		}
	
		.tit_rt {
			display: flex;
			align-items: center;
	
		}
	
		.more {
			height: 48rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #3FAA73;
			line-height: 48rpx;
			margin-right: 8rpx;
		}
	}

	.ticket-order-page {
		box-sizing: border-box;
		min-height: 100vh;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		background-color: #f7f9fa;

		.tabs {
			position: sticky;
			top: 0;
			// width: 100%;
			padding: 16rpx 32rpx;
			background-color: #f7f9fa;

			.tab_contant {
				background-color: #f7f9fa;
			}
		}

		.ticket-list {
			height: calc(100% - 120rpx);
			padding: 0 32rpx;
		}

		.ticket-item {
			background: #ffffff;
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			padding: 24rpx;
			margin-top: 24rpx;
			
			.ticket-title {
				display: flex;
				align-items: center;
			
				.title {
					flex: 1;
					margin-right: 24rpx;
					display: flex;
					align-items: center;
			
					image {
						display: block;
						width: 40rpx;
						height: 40rpx;
						margin-right: 16rpx;
						border-radius: 8rpx;
					}
					text {
						font-size: 28rpx;
						font-weight: 400;
						color: #87A198;
						line-height: 40rpx;
					}
				}
				.status {
					font-size: 28rpx;
					font-weight: 600;
					color: rgba(0, 0, 0, 0.8);
					line-height: 40rpx;
					&_1 {
						color: #EE9802;
					}
					&_2 {
						color: rgba(0, 0, 0, 0.7);
					}
				}
			}

			.ticket-card {
					margin-top: 24rpx;
					padding: 24rpx;
					box-sizing: border-box;
					min-height: 148rpx;
					background: #F3F6F5;
					border-radius: 16rpx 16rpx 16rpx 16rpx;
			
					.top {
						display: flex;
						justify-content: space-between;
			
						.ticket-name {
							font-size: 32rpx;
							font-weight: 400;
							color: rgba(0, 0, 0, 0.8);
							line-height: 44rpx;
							display: flex;
							align-items: center;
							
						}
			
						.ticket-price {
							font-size: 32rpx;
							font-family: D-DIN-Bold, D-DIN;
							font-weight: 700;
							color: rgba(0, 0, 0, 0.8);
							line-height: 34rpx;
						}
					}
			
					.bottom {
						margin-top: 16rpx;
						display: flex;
						justify-content: space-between;
			
						.ticket-validity {
			        font-size: 28rpx;
			        font-weight: 400;
			        color: #3FAA73;
			        line-height: 40rpx;
							display: flex;
							align-items: center;
							.tcan {
			          font-size: 28rpx;
			          font-weight: 400;
			          color: rgba(0,0,0,0.5);
			          line-height: 40rpx;
								margin-left: 16rpx;
			          margin-right: 16rpx;
							}
						}
			      .tnum {
							margin-left: 16rpx;
			        font-size: 28rpx;
			        font-weight: 400;
			        color: rgba(0,0,0,0.7);
			        line-height: 40rpx;
						}
					}
				}
			}
			
      .pay {
        margin-top: 24rpx;
        text-align: right;
        font-size: 28rpx;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.7);
        line-height: 40rpx;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        text:last-child {
          font-size: 32rpx;
          font-family: D-DIN-Bold, D-DIN;
          font-weight: 700;
          color: rgba(0, 0, 0, 0.7);
          line-height: 34rpx;
        }
        .status_1 {
          color: #EE9802 !important;
        }
        .status_2 {
          color: rgba(0, 0, 0, 0.7);
        }
      }

		.btns {
			margin-top: 32rpx;
			display: flex;
			justify-content: flex-end;
		
			.btn {
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: center;
				min-width: 148rpx;
				padding: 12rpx 32rpx;
				height: 64rpx;
				border: 0;
				font-size: 28rpx;
				font-weight: 700;
				border-radius: 44px;
		
				&:not(:last-child) {
					margin-right: 16rpx;
				}
		
				&.outline {
					border: 2rpx solid #b7c1ca;
					color: #777f8f;
				}
		
				&.icon-service {
					image {
						display: block;
						width: 34rpx;
						height: 34rpx;
						margin-right: 14rpx;
					}
				}
		
				&.primary {
					background: #3FAA73;
					border: 2rpx solid #3FAA73;
					color: #fff;
		      font-weight: 700;
				}
			}
		}
	}
</style>